package com.hjlsoft.aftp.network;

import java.io.IOException;

import com.hjlsoft.aftp.config.AftpConfig;
import com.hjlsoft.aftp.ins.AftpResultCode;

public abstract class AbstractResponse implements Response {

	private static final byte[] CRLF = "\r\n".getBytes();
	
	protected AftpConfig config;
	
	private AftpResultCode resultCode;

	private void writeResultCode1(AftpResultCode resultCode) throws IOException {
		this.resultCode = resultCode;
		String s = String.format("%d %s", resultCode.getCode(), resultCode.getMessage());
		writeLine(s);
	}
	
	public void writeSuccessDataEnd(String data) throws IOException {
		writeResultCode1(AftpResultCode.SUCCESS);
		writeLine(data);
		writeLine();
	}

	public void writeResultCodeEnd(AftpResultCode resultCode) throws IOException {
		writeResultCode1(resultCode);
		writeLine();
	}
	
	private void writeLine(String data) throws IOException {
		write(data.getBytes(config.getCharset()));
		writeLine();
	}

	private void writeLine() throws IOException {
		write(CRLF);
	}

	public AbstractResponse(AftpConfig config) {
		super();
		this.config = config;
	}

	public AftpResultCode getResultCode() {
		return resultCode;
	}

}
